<template>
  <div>
    <el-dialog
      v-loading.lock="loading"
      class="base-dialog system-user-dialog"
      :append-to-body="true"
      title="文件管理信息"
      align="center"
      :close-on-click-modal="false"
      :before-close="cancel"
      :visible.sync="innerDialogFormVisible"
    >
      <el-form
        ref="formData"
        class="base-pipeline-layout system-user-form"
        label-width="100px"
        :model="formData"
        :rules="formDataRules"
        status-icon
      >
        <el-form-item
          label="所属文件夹"
          :label-width="formLabelWidth"
          prop="archiveDicId"
          :error="errorMsg.archiveDicId"
        >
          <el-select
            v-model="formData.archiveDicId"
            placeholder="请选择"
            @change="archiveDicChange"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="文件编号"
          :label-width="formLabelWidth"
          prop="archiveNum"
          :error="errorMsg.archiveNum"
        >
          <el-input v-model="formData.archiveNum" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="文件名称"
          :label-width="formLabelWidth"
          prop="archiveName"
          :error="errorMsg.archiveName"
        >
          <el-input
            v-model="formData.archiveName"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item
          label="文件说明"
          :label-width="formLabelWidth"
          :error="errorMsg.remark"
        >
          <el-input
            v-model="formData.remark"
            type="textarea"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item
          label="上传附件"
          :label-width="formLabelWidth"
          style="width: 100%"
          prop="fileWarehouse"
        >
          <el-button
            v-loading="uploadLoad"
            style="float: left"
            size="small"
            icon="el-icon-paperclip"
            type="primary"
            @click="choiseFile()"
            >点击上传</el-button
          >
          <span
            style="
              margin-left: 5px;
              font-size: 13px;
              color: orange;
              float: left;
            "
            >只能上传pdf,doc,docx,xls,xlsx,jpg,bmp,png格式的文件，最多上传5个文件，单个文件大小不能超过30M
          </span>
          <el-upload
            ref="upload"
            style="display: none"
            class="base-upload"
            name="FilePath"
            :multiple="true"
            action
            :headers="headers"
            :show-file-list="false"
            :show-upload-list="false"
            :accept="accept"
            :limit="limit"
            :before-upload="beforeUpload"
            :on-change="upload"
            :auto-upload="false"
            :file-list="fileList"
            :on-exceed="handleExceed"
          ></el-upload>
          <el-table
            ref="table"
            v-loading="tableLoading"
            :data="formData.fileWarehouse"
            style="width: 100%"
            height="300px"
          >
            <el-table-column label="序号" width="50px">
              <template slot-scope="scope"
                ><span>{{ scope.$index + 1 }}</span></template
              >
            </el-table-column>
            <el-table-column
              prop="originalFileName"
              label="文件名称"
            ></el-table-column>
            <el-table-column label="操作" width="140">
              <template slot-scope="{ row }">
                <div class="base-table-operation">
                  <el-link type="danger" @click="deleteUnit(row)">删除</el-link>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item
          label="文件状态"
          :label-width="formLabelWidth"
          prop="archiveStatus"
          :error="errorMsg.archiveStatus"
        >
          <el-select
            v-model="formData.archiveStatus"
            placeholder="请选择"
            @change="archiveStatusChange"
          >
            <el-option
              v-for="item in optionsStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="formData.archiveStatus === 1"
          style="width: 100%"
          label="权限设置"
          :label-width="formLabelWidth"
          prop="userIdList"
          :error="errorMsg.userIdList"
        >
          <el-table
            ref="table"
            :data="userTable"
            style="width: 100%"
            height="300px"
          >
            <el-table-column label="用户姓名" prop="id">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.id"
                  placeholder="请选择用户"
                  filterable
                  @change="userChange(scope.$index)"
                >
                  <el-option
                    v-for="item in userList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="用户名" prop="account" />
            <el-table-column label="手机号" prop="mobile" />
            <el-table-column label="操作" width="140">
              <template slot-scope="scope">
                <div class="base-table-operation">
                  <el-link type="danger" @click="deleteUser(scope.$index)"
                    >删除</el-link
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
          <el-button
            v-if="formData.archiveStatus == 1"
            type="primary"
            @click="addUser"
            >添加用户</el-button
          >
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="onSubmit('formData')"
          >保 存</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserListNoPage } from "../../../api/PermissionUser.js";
import {
  GetArchiveNumber,
  create,
  update,
  Get,
} from "../../../api/Archive/Archive.js";
import { formdataify } from "@/utils/index";
import { getToken } from "@/utils/auth";
import { GetListNoPage } from "../../../api/Archive/ArchiveDic";
export default {
  name: "ArchiveEdit",
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },
    archiveDicId: {
      type: String,
      default: "",
    },
    id: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      loading: false,
      uploadLoad: false,
      tableLoading: false,
      searchUserLoading: false,
      innerDialogFormVisible: false,
      limit: 5,
      fileSize: 30,
      businessType: 140,
      archiveNum: "",
      formLabelWidth: "100px",
      imgAccept: ".jpg,.bmp,.png",
      accept: ".pdf,.doc,.docx,.xls,.xlsx,.png,.jpg,.bmp",
      headers: { Authorization: getToken() },
      options: [],
      userList: [],
      fileList: [],
      userTable: [],
      optionsStatus: [
        { value: 0, label: "非受控" },
        { value: 1, label: "受控" },
      ],
      initData: {
        id: 0,
        archiveNum: "",
        archiveName: "",
        archiveStatus: 0,
        remark: "",
        archiveDicId: "",
        operatorId: 0,
        generateState: 0,
        operatorDate: null,
        fileWarehouse: [],
        userIdList: [],
      },
      formData: {
        id: 0,
        archiveNum: "",
        archiveName: "",
        archiveStatus: 0,
        generateState: 0,
        remark: "",
        archiveDicId: this.archiveDicId,
        operatorId: 0,
        operatorDate: null,
        fileWarehouse: [],
        userIdList: [],
      },
      formDataRules: {
        archiveNum: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        archiveName: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        archiveStatus: [
          {
            required: true,
            trigger: "blur",
          },
        ],
        remark: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        archiveDicId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        fileWarehouse: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
      },
      initErrorMsg: {
        archiveNum: "",
        archiveName: "",
        archiveStatus: "",
        remark: "",
        archiveDicId: "",
        operatorId: "",
        operatorDate: "",
      },
      errorMsg: {
        archiveNum: "",
        archiveName: "",
        archiveStatus: "",
        remark: "",
        archiveDicId: "",
        operatorId: "",
        operatorDate: "",
      },
    };
  },
  watch: {
    innerDialogFormVisible(val) {
      this.$emit("update:dialogFormVisible", val);
    },
  },
  created() {
    this.innerDialogFormVisible = this.dialogFormVisible;
    this.init();
  },
  methods: {
    userChange(index) {
      var user = this.userList.find((x) => x.id === this.userTable[index].id);
      this.userTable[index].account = user.account;
      this.userTable[index].mobile = user.mobile;
    },
    // 添加用户
    addUser() {
      this.userTable.push({ id: "", account: "", mobile: "" });
    },
    // 删除用户
    deleteUser(index) {
      this.userTable.splice(index, 1);
    },
    // 选择所属文件夹
    archiveDicChange(val) {
      this.GetNumber(val);
    },
    // 文件状态改变出现权限设置
    archiveStatusChange(val) {
      if (Number(val) === 0) {
        this.userTable = [];
        this.formData.userIdList = [];
      } else {
        getUserListNoPage().then((res) => {
          this.userList = res.data;
          var user = this.userList.find(
            (x) => x.id === this.$store.getters.currentUserId
          );
          if (!this.id) {
            this.userTable.push({
              id: this.$store.getters.currentUserId,
              account: user.account,
              mobile: user.mobile,
            });
          }
        });
      }
    },
    init() {
      GetListNoPage({ parentId: 0 }).then((res) => {
        this.options = res.data;
      });
      if (this.id) {
        Get({ id: this.id }).then((res) => {
          this.formData = res.data;
          this.archiveNum = this.formData.archiveNum;
          this.userTable = res.data.userList;
          this.fileList = res.data.fileWarehouse;
          for (let i = 0; i < this.formData.fileWarehouse.length; i++) {
            this.formData.fileWarehouse[i].index = i;
          }
          this.archiveStatusChange(this.formData.archiveStatus);
        });
      } else {
        this.GetNumber(this.archiveDicId);
      }
    },
    GetNumber(archiveDicId) {
      if (archiveDicId) {
        GetArchiveNumber({ id: archiveDicId }).then((res) => {
          this.formData.archiveNum = res.data;
          this.archiveNum = this.formData.archiveNum;
        });
      }
    },
    choiseFile() {
      this.$refs["upload"].$refs["upload-inner"].handleClick();
    },
    upload(file, fileList) {
      var verify = this.beforeUpload(file);
      this.fileList = fileList;
      if (!verify) {
        this.fileList.pop();
        return false;
      }
      const obj = {
        businessType: this.businessType,
        file: file.raw,
      };
      this.tableLoading = true;
      this.$forceUpdate();
      const form = formdataify(obj);
      this.Base.uploadFileInfo(form)
        .then((res) => {
          this.tableLoading = false;
          var testmsg = file.name.substring(file.name.lastIndexOf("."));
          const fileTypes = this.imgAccept.split(",");
          const img = fileTypes.includes(testmsg);
          var data = {
            index: this.formData.fileWarehouse
              ? this.formData.fileWarehouse.length
              : 0,
            storageFileName: res.data.newFileName,
            fileTpyeCode: 2,
            filePath: res.data.filePath,
            originalFileName: res.data.fileName,
          };
          if (img) {
            data.fileTpyeCode = 1;
          }
          this.formData.fileWarehouse.push(data);
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 ${this.limit} 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    // 移除
    deleteUnit(row) {
      this.$confirm("是否确认删除，此操作不可逆！", "删除", {
        type: "warning",
        confirmButtonText: "删除",
        okType: "danger",
        center: true,
        cancelButtonText: "取消",
        beforeClose: (action, instance, done) => {
          if (action === "confirm") {
            let indexToDelete = -1;
            for (let i = 0; i < this.formData.fileWarehouse.length; i++) {
              if (this.formData.fileWarehouse[i].index === row.index) {
                console.log("ss");
                indexToDelete = i;
                break;
              }
            }
            if (indexToDelete !== -1) {
              this.formData.fileWarehouse.splice(indexToDelete, 1);
              this.fileList = this.formData.fileWarehouse; // 通过创建新数组来删除元素
            }
            instance.confirmButtonLoading = false;
            done();
          } else {
            instance.confirmButtonLoading = false;
            done();
          }
        },
      });
    },
    // 上传校验 or 大小
    beforeUpload(file) {
      const fileTypes = this.accept.split(",");
      const fileExtension = file.name.substring(file.name.lastIndexOf("."));
      const checkFormat = fileTypes.includes(fileExtension.toLowerCase());
      const maxSizeInBytes = this.fileSize * 1024 * 1024; // 30MB in bytes
      const isFileSizeValid = file.size <= maxSizeInBytes;

      if (!checkFormat) {
        this.uploadLoad = false;
        this.$message.error(`请选择${this.accept}格式`);
      }

      if (!isFileSizeValid) {
        this.uploadLoad = false;
        this.$message.error(`文件必须小于${this.fileSize}MB！`);
      }

      return checkFormat && isFileSizeValid;
    },
    cancel() {
      this.$emit("close");
      this.innerDialogFormVisible = false;
    },
    closeDialog() {
      this.cancel();
    },
    onSubmit() {
      if (this.formData.archiveStatus === 1) {
        if (
          this.userTable === undefined ||
          this.userTable === null ||
          this.userTable.length === 0
        ) {
          this.$message.error("权限设置不能为空");
          return false;
        }
      }
      this.formData.userIdList = this.userTable.map((x) => x.id);
      if (this.id) {
        if (
          this.formData.archiveNum !== this.archiveNum &&
          this.formData.generateState === 0
        ) {
          this.formData.generateState = 1;
        }
      } else {
        if (this.formData.archiveNum !== this.archiveNum) {
          this.formData.generateState = 1;
        }
      }
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);
          if (this.formData.id <= 0) {
            create(this.formData)
              .then((res) => {
                if (res.code === 200) {
                  this.closeDialog();
                } else {
                  this.showValidateMsgCheck(res);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          } else {
            update(this.formData)
              .then((res) => {
                if (res.code === 200) {
                  this.closeDialog();
                } else {
                  this.showValidateMsgCheck(res);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          }
        } else {
          return false;
        }
      });
    },
    showValidateMsgCheck(res) {
      if (res.msg) {
        this.Helper.showValidateMsg("archiveNum", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("archiveName", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("archiveStatus", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("remark", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("archiveDicId", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("operatorId", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("operatorDate", this.errorMsg, res.msg);
      }
    },
  },
};
</script>
